package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.validator.QueryHelpMybatisPlus;
import cn.cdeden.knowledge.domain.*;
import cn.cdeden.knowledge.enums.TreeEnum;
import cn.cdeden.knowledge.enums.TreeTypeEnum;
import cn.cdeden.knowledge.mapper.FileTemplateTreeMapper;
import cn.cdeden.knowledge.mapper.SysFormDocTempMapper;
import cn.cdeden.knowledge.service.SysFormDocTempService;
import cn.cdeden.knowledge.utils.PageUtil;
import cn.cdeden.resource.api.RemoteFileService;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.domain.vo.RemoteUserVo;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
* @author Chen
* @date 2023-12-26
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = SysFormDocTempService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SysFormDocTempServiceImpl extends ServiceImpl<SysFormDocTempMapper, SysFormDocTemp> implements SysFormDocTempService {

    // private final RedisUtils redisUtils;
    private final SysFormDocTempMapper sysFormDocTempMapper;
//    private final FileStorageUtils fileStorageUtils;

//    private final EnterpriseTemplateTreeMapper enterpriseTemplateTreeMapper;

    private final FileTemplateTreeMapper fileTemplateTreeMapper;

    private final RemoteUserService sysUserService;

    @Override
    public TableDataInfo<SysFormDocTempDto> queryAll(SysFormDocTempQueryParam query, Pageable pageable) {
        IPage<SysFormDocTemp> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<SysFormDocTemp> page = sysFormDocTempMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
//        storageConvert(page);
        return MapstructUtils.convertTableDataInfo(TableDataInfo.build(page), SysFormDocTempDto.class);
    }

//    public void storageConvert(IPage<SysFormDocTemp> formDataIPage){
//        for (SysFormDocTemp formData : formDataIPage.getRecords()) {
//            if (formData.getCoverStorage() != null){
//                Storage storage = fileStorageUtils.getByID(formData.getCoverStorage().toString());
//                String imageUrl = storage.getPath("1");
//                String s = ImageFileUrlUtil.imageFile(imageUrl);
//                formData.setCoverStorage(s);
//            }
//        }
//    }

    @Override
    public List<SysFormDocTempDto> queryAll(SysFormDocTempQueryParam query){
        return MapstructUtils.convert(sysFormDocTempMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), SysFormDocTempDto.class);
    }

    @Override
    public SysFormDocTemp getById(Long id) {
        return sysFormDocTempMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public SysFormDocTempDto findById(Long id) {
        return MapstructUtils.convert(getById(id), SysFormDocTempDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysFormDocTemp insert(SysFormDocTempDto resources){
//        MultipartFile coverFile = resources.getCoverFile();
//        Storage storage = new Storage();
//        if (coverFile != null){
//            String suffix = FileUtil.getSuffix(coverFile.getOriginalFilename());
//            //上传封面
//            if (suffix.equals("jpg") || suffix.equals("png")) {
//                FileUserDto user = FileUserUtils.getUser();
//                storage = fileStorageUtils.create(user.getId().toString(), user.getUsername(), StorageFolderTypeEnum.PUBLIC_BUCKET.getCode(), coverFile, FileEnums.SYSTEM_SETTINGS, null);
//                resources.setCoverStorage(String.valueOf(storage.getStorageId()));
//            } else {
//                throw new RuntimeException("文件上传格式错误");
//            }
//        }
        SysFormDocTemp entity = MapstructUtils.convert(resources, SysFormDocTemp.class);
        sysFormDocTempMapper.insert(entity);
        if (resources.getStatus().equals("publish")) {
            //模板库新增
            FileTemplateTree templateTree = new FileTemplateTree();
            templateTree.setParentId(Long.valueOf(resources.getApplyType()))
                    .setType(TreeTypeEnum.RICHTEXT.getType())
                    .setState(TreeEnum.ENTERPRISE.getType())
                    .setFileStorage(entity.getId().toString())
                    .setImageStorage(entity.getCoverStorage())
                    .setRealName(resources.getFormName())
                    .setDeptId(resources.getDeptId())
                    .setSuffix(TreeTypeEnum.RICHTEXT.getType());
            fileTemplateTreeMapper.insert(templateTree);
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysFormDocTemp updateById(SysFormDocTempDto resources){

//        if (null !=  resources.getCoverFile()){
//            MultipartFile coverFile = resources.getCoverFile();
//            String suffix = FileUtil.getSuffix(coverFile.getOriginalFilename());
//            //上传封面
//            if (suffix.equals("jpg") || suffix.equals("png")) {
//                FileUserDto user = FileUserUtils.getUser();
//                Storage storage = fileStorageUtils.create(user.getId().toString(), user.getUsername(), StorageFolderTypeEnum.PUBLIC_BUCKET.getCode(), coverFile, FileEnums.SYSTEM_SETTINGS, null);
//                resources.setCoverStorage(String.valueOf(storage.getStorageId()));
//            } else {
//                throw new RuntimeException("文件上传格式错误");
//            }
//        }

        SysFormDocTemp entity = MapstructUtils.convert(resources, SysFormDocTemp.class);
        int ret = sysFormDocTempMapper.updateById(entity);
//        if (entity.getCoverStorage() != null){
//            Storage storage = fileStorageUtils.getByID(entity.getCoverStorage());
//            String imageUrl = storage.getPath("1");
//            String s = ImageFileUrlUtil.imageFile(imageUrl);
//            entity.setCoverStorage(s);
//        }
        SysFormDocTemp data = sysFormDocTempMapper.selectById(entity.getId());
        //如果设置为公共模板
        if (data.getStatus().equals("publish")) {
            List<FileTemplateTree> list = fileTemplateTreeMapper.selectList(new LambdaQueryWrapper<FileTemplateTree>().eq(FileTemplateTree::getFileStorage, data.getId()));
            if (list.size() > 0) {
                fileTemplateTreeMapper.selectList(new LambdaUpdateWrapper<FileTemplateTree>().eq(FileTemplateTree::getFileStorage, entity.getId()).set(FileTemplateTree::getParentId, entity.getApplyType()).set(FileTemplateTree::getRealName, data.getFormName()).set(FileTemplateTree::getImageStorage, entity.getCoverStorage()));
            } else {
                //模板库新增
                FileTemplateTree templateTree = new FileTemplateTree();
                templateTree.setParentId(Long.valueOf(data.getApplyType()))
                        .setType(TreeTypeEnum.RICHTEXT.getType())
                        .setState(TreeEnum.ENTERPRISE.getType())
                        .setImageStorage(data.getCoverStorage())
                        .setFileStorage(data.getId().toString())
                        .setDeptId(data.getDeptId())
                        .setRealName(data.getFormName())
                        .setSuffix(TreeTypeEnum.RICHTEXT.getType());
                fileTemplateTreeMapper.insert(templateTree);
            }
        }
        else {
            fileTemplateTreeMapper.delete(new LambdaUpdateWrapper<FileTemplateTree>().eq(FileTemplateTree::getFileStorage, entity.getId()));
        }
        // delCaches(resources.id);
        return entity;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Long> ids){
        // delCaches(ids);
        for (Long id : ids) {
//            enterpriseTemplateTreeMapper.lambdaUpdate().eq(EnterpriseTemplateTree::getFileStorage, id)
//                    .eq(EnterpriseTemplateTree::getState, TreeEnum.ENTERPRISE.getType())
//                    .eq(EnterpriseTemplateTree::getType, TreeTypeEnum.RICHTEXT.getType())
//                    .eq(EnterpriseTemplateTree::getType, TreeTypeEnum.RICHTEXT.getType()).remove();
        }
        return sysFormDocTempMapper.deleteBatchIds(ids);
    }

//    @Override
//    public SysFormDocTemp selectSysDeployFormByDeployId(String deployId) {
//        return sysFormDocTempMapper.selectSysDeployFormByDeployId(deployId);
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Long id){
        Set<Long> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /**
     * 复制表单模板
     * @param id            模板id
     * @param formType      表单复制到模板库（0：个人  1：企业）
     * @param userId        用户id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysFormDocTemp copySysFormDocTempById(Long id, Integer formType, Long userId){
        SysFormDocTemp sysFormDocTemp = baseMapper.selectById(id);
        if (ObjectUtil.isNull(sysFormDocTemp))throw new RuntimeException("此表单模板文件为null");
        if (formType.intValue() == 0){
            //个人
            RemoteUserVo remoteUserVo = sysUserService.selectUserByUserId(userId);
            if (ObjectUtil.isNull(remoteUserVo))throw new RuntimeException("用户为null");
            sysFormDocTemp.setId(null)
                    .setCreateBy(remoteUserVo.getUserName())
                    .setCreateId(remoteUserVo.getUserId().toString())
                    .setFormType(0)
                    .setCreateTime(new Date());
        } else if (formType.intValue() == 1) {
            //企业
            RemoteUserVo remoteUserVo = sysUserService.selectUserByUserId(userId);
            sysFormDocTemp.setId(null)
                .setCreateBy(remoteUserVo.getUserName())
                .setCreateId(remoteUserVo.getUserId().toString())
                    .setFormType(1)
                    .setCreateTime(new Date());
        }else {
            throw new RuntimeException("不存在此formType类型");
        }
        baseMapper.insert(sysFormDocTemp);
        return sysFormDocTemp;
    }
    /*
    private void delCaches(Long id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Long> ids) {
        for (Long id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<SysFormDocTempDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (SysFormDocTempDto sysFormDocTemp : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("表单名称", sysFormDocTemp.getFormName());
              map.put("表单编码", sysFormDocTemp.getFormCode());
              map.put("表单JSON", sysFormDocTemp.getFormJson());
              map.put("表单图标", sysFormDocTemp.getFormIcon());
                map.put(" coverStorage",  sysFormDocTemp.getCoverStorage());
              map.put("表单类型", sysFormDocTemp.getFormType());
                map.put(" applyType",  sysFormDocTemp.getApplyType());
              map.put("表单配置项", sysFormDocTemp.getOptions());
              map.put("创建编号", sysFormDocTemp.getCreateId());
              map.put("创建者", sysFormDocTemp.getCreateBy());
              map.put("创建日期", sysFormDocTemp.getCreateTime());
              map.put("更新编号", sysFormDocTemp.getUpdateId());
              map.put("更新者", sysFormDocTemp.getUpdateBy());
              map.put("更新时间", sysFormDocTemp.getUpdateTime());
              map.put("删除编号", sysFormDocTemp.getDeleteId());
              map.put("删除者", sysFormDocTemp.getDeleteBy());
              map.put("删除时间", sysFormDocTemp.getDeleteTime());
                map.put(" deleteType",  sysFormDocTemp.getDeleteType());
                map.put(" coverUrl",  sysFormDocTemp.getCoverUrl());
                map.put(" previews",  sysFormDocTemp.getPreviews());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
